import Vue from "vue";
import Vuex from "vuex";
import mutations from "./mutations";
import actions from "./actions";
import { util } from '../common/util.js'
import { config } from '../config.js'

Vue.use(Vuex);

let modules = {};
// 获取当前文件夹下modules文件夹的js文件列表并赋值modules对象
const files = require.context('./modules/', false, /\.js$/);
files.keys().forEach(key => {
  if(key.indexOf('index') < 0){
    modules[key.replace('./', '').replace('.js', '')] = files(key).default;
  }
});

export const store = new Vuex.Store({
  state: {
		token: util.getLocalStorage('token_' + config.appName) || '',
    debugSetting: util.getLocalStorage('debugSetting_' + config.appName) || {},
  },
  getters: {
		getToken: state => state.token, // es6箭头函数写法
    getDebugSetting: (state) => {
			// 判断是否使用mock假数据或指定的服务器后台
			if(JSON.stringify(state.debugSetting) != '{}') {
				if(state.debugSetting.mode && state.debugSetting.mode == 1){ // 使用mock假数据
					if(state.debugSetting.display) 
						console.log('APIPath:', config.mockAPIPath);
					return Object.assign(state.debugSetting, {
						APIPath: config.mockAPIPath,
						resourcePath: config.mockResourcePath
					});
				}else { // 使用服务器链接真实后台
					if(state.debugSetting.display) 
						console.log('APIPath:', (state.debugSetting.APIPath && state.debugSetting.APIPath != '') ? state.debugSetting.APIPath : config.APIPath);
					return Object.assign(state.debugSetting, {
						APIPath: (state.debugSetting.APIPath && state.debugSetting.APIPath != '') ? state.debugSetting.APIPath : config.APIPath,
						resourcePath: (state.debugSetting.resourcePath && state.debugSetting.resourcePath != '') ? state.debugSetting.resourcePath : config.resourcePath
					});
				}
			}else{
				if(state.debugSetting.display) 
					console.log('APIPath:', config.APIPath);
				return {
					display: false,
					APIPath: config.APIPath,
					resourcePath: config.resourcePath
				};
			}
		},
  },
  mutations: mutations,
  actions: actions,
  modules: modules
});
